package cn.serein.charging.order.config;


import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMQConfiguration {

    // 定义交换机常量名称
    public static final String EXCHANGE_NAME = "charging_order_exchange";

    // 定义队列常量名称
    public static final String QUEUE_NAME = "charging_order_queue";

    // 定义路由常量名称
    public static final String ROUTING_KEY = "charging_order_routing_key";

    // 死信队列
    private static final String DEAD_LETTER_EXCHANGE_NAME = "dead_letter_charging_order_exchange";

    public static final String DEAD_LETTER_QUEUE_NAME = "dead_letter_charging_order_queue";

    private static final String DEAD_LETTER_ROUTING_KEY = "dead_letter_charging_order_routing_key";


    // 定义交换机Bean对象
    @Bean
    public DirectExchange orderExchange(){

        // 持久化
        Boolean durable = true;

        // 自动删除
        Boolean autoDelete = false;

        return new DirectExchange(EXCHANGE_NAME, durable, autoDelete);
    }

    // 定义队列Bean对象
    @Bean
    public Queue orderQueue(){
        // 参数  设置消息的生存时间
        Map<String, Object> args = new HashMap<>();

        Integer ttl = 60 * 1000;
        args.put("x-message-ttl", ttl);


        // 设置死信队列
        args.put("x-dead-letter-exchange", DEAD_LETTER_EXCHANGE_NAME);
        args.put("x-dead-letter-routing-key", DEAD_LETTER_ROUTING_KEY);
        args.put("x-queue-mode","lazy");


        // 持久化
        Boolean durable = true;

        return new Queue(QUEUE_NAME, durable,true,false,args);
    }


    // 定义路由Bean对象
//    @Bean
//    public String orderRoutingKey(){
//        return ROUTING_KEY;
//    }

    // 将交换机与队列通过路由绑定
    @Bean
    public Binding orderBinding(){

        return BindingBuilder.
                bind(orderQueue()).
                to(orderExchange()).
                with(ROUTING_KEY);

    }

    // 上面为正常队列的配置

    // 死信队列
    @Bean
    public DirectExchange deadLetterExchange(){

        // 持久化
        Boolean durable = true;

        // 自动删除
        Boolean autoDelete = false;
        return new DirectExchange(DEAD_LETTER_EXCHANGE_NAME, durable, autoDelete);
    }
    @Bean
    public Queue deadLetterQueue(){
        // 持久化
        Boolean durable = true;
        return new Queue(DEAD_LETTER_QUEUE_NAME, durable);
    }

    @Bean
    public Binding deadLetterBinding(){
        return BindingBuilder.
                bind(deadLetterQueue()).
                to(deadLetterExchange()).
                with(DEAD_LETTER_ROUTING_KEY);
    }


}
